package cd.cdyb.sms.controller;


import cd.cdyb.sms.dto.PageResult;
import cd.cdyb.sms.dto.RechargeDto;
import cd.cdyb.sms.dto.expand.ExRechargeDto;
import cd.cdyb.sms.dto.query.RechargeQueryDto;
import cd.cdyb.sms.exception.BusinessException;
import cd.cdyb.sms.service.RechargeService;
import cd.cdyb.sms.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lin
 * @since 2024-05-16
 */
@RestController
@RequestMapping("/recharge")
public class RechargeController {

    @Resource
    private RechargeService rechargeService;


    /**
     * 新增
     */
    @PostMapping("/insertRecharge")
    public void insertRecharge(@RequestBody @Valid RechargeDto rechargeDto) throws BusinessException {
        rechargeDto.setOperatorId(UserUtils.getCurrentUserId());
        rechargeDto.setOperatorName(UserUtils.getCurrentName());
        if (rechargeDto.getWhetherInvoice() && StringUtils.isBlank(rechargeDto.getInvoiceNumber())) {
            throw new BusinessException("发票编号不能为空");
        }
        rechargeService.insertRecharge(rechargeDto);
    }

    /**
     * 乘
     */
    @PostMapping("/multiply")
    public BigDecimal multiply(@RequestBody ExRechargeDto exRechargeDto) throws BusinessException {
        if (Objects.isNull(exRechargeDto.getEachAmount())) {
            throw new BusinessException("每条短信费用不能为空");
        }
        if (Objects.isNull(exRechargeDto.getRechargeQuantity())) {
            throw new BusinessException("数量不能为空");
        }
        BigDecimal bigDecimal = exRechargeDto.getEachAmount()
                .multiply(new BigDecimal(exRechargeDto.getRechargeQuantity()))
                .setScale(2, RoundingMode.HALF_UP);
        return bigDecimal;
    }


    /**
     * 客户端分页
     */
    @PostMapping("/findRechargePageWithClient")
    public PageResult<RechargeDto> findRechargePageWithClient(@RequestBody RechargeQueryDto rechargeQueryDto) throws BusinessException {
        rechargeQueryDto.setCompanyId(UserUtils.getCompanyId());
        return rechargeService.findRechargePageWithClient(rechargeQueryDto);
    }

    /**
     * 管理端分页
     */
    @PostMapping("/findRechargePageWithAdmin")
    public PageResult<RechargeDto> findRechargePageWithAdmin(@RequestBody RechargeQueryDto rechargeQueryDto) {
        return rechargeService.findRechargePageWithClient(rechargeQueryDto);
    }

    /**
     * 开票
     */
    @PostMapping("/invoice")
    public void invoice(@RequestBody RechargeDto rechargeDto) throws BusinessException {
        rechargeService.invoice(rechargeDto);
    }

}

